package com.xnyzc.lhy.common.component.config.security;

import com.alibaba.fastjson.JSONObject;
import com.xnyzc.lhy.common.constant.CommonConstant;
import com.xnyzc.lhy.common.entity.Rv;
import com.xnyzc.lhy.common.penum.EErrorCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Description:
 * @Author: scootXin
 * @Date: 2019/3/13 10:38
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    public JwtAuthenticationTokenFilter(JwtTokenUtil jwtTokenUtil) {
        this.jwtTokenUtil = jwtTokenUtil;
    }

    public JwtAuthenticationTokenFilter() {
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException,
            IOException {
        String authHeader = request.getHeader(CommonConstant.REQ_HEADER);
        String tokenHead = CommonConstant.TOKEN_SPLIT;
        if (authHeader != null && authHeader.startsWith(tokenHead)) {
            final String authToken = authHeader.substring(tokenHead.length());

            // 效验token是否有效
            if (!jwtTokenUtil.validateUserToken(authToken)) {
                responseInfo(response);
                return;
            }

            TokenUser tokenUser = JwtTokenUtil.getUserFromToken(authToken);
            if (tokenUser != null && SecurityContextHolder.getContext().getAuthentication() == null) {

                if (jwtTokenUtil.validateToken(authToken, tokenUser)) {
                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(tokenUser, null, tokenUser
                            .getAuthorities());
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
                // token 过期
                else {
                    responseInfo(response);
                    return;
                }
            }
        }
        chain.doFilter(request, response);
    }

    /**
     * 响应信息
     *
     * @param response
     * @throws IOException
     */
    private void responseInfo(HttpServletResponse response) throws IOException {
        response.setHeader("Content-type", "text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter pw = response.getWriter();
        pw.write(Rv.wrap(EErrorCode.userInforExpire, new JSONObject()).toString());
        pw.flush();
        pw.close();
    }
}
